import { Injectable } from '@nestjs/common';
import { Method, Type } from 'src/common/enum';
import { GenerateDto } from 'src/dto/generate.dto';
import { Permission } from 'src/entity/permission.entity';

const fs = require('fs');

@Injectable()
export class GenerateService {
  async create(generateDto: GenerateDto) {
    let name = this.titleCase(generateDto.tableName);
    return this.generate(name, generateDto.jsonData, generateDto.menuName);
  }

  titleCase(str: string) {
    return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
  }

  async generate(entityClassName: string, jsonData: any, menuName: string) {
    let lowEntityClassName = entityClassName.toLowerCase();

    // 1.根据jsonData拼接column
    let tempDto = ``;
    let tempEntity = ``;
    let queryDto = ``;

    if (Array.isArray(jsonData)) {
      jsonData.map((item) => {
        tempDto = `${tempDto}
        ${item.row}:${item.jsType}
        `;

        tempEntity = `${tempEntity}
        @${item.tag}({comment:"${item.comment}",nullable:${item.nullable},unique:${item.unique},default:${item.defaultValue},type:${item.typeValue == 'decimal' ? '"' + item.typeValue + '"' + ',precision: 10, scale: 2' : '"' + item.typeValue + '"'}, })
        ${item.row}:${item.jsType}
        `;
        // 查询dto
        if (item.queryType == '1') {
          queryDto = `${queryDto}
          ${item.row}:${item.jsType}`;
        }
      });
    }

    // 读取并写入query.dto
    let filePath = 'src/template/dto/query-template.dto.template';

    let res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('// ${query}', queryDto);

    fs.writeFileSync(`src/dto/query-${lowEntityClassName}.dto.ts`, res);
    // 2.读取并写入create.dto
    filePath = 'src/template/dto/create-template.dto.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('// ${dto}', tempDto);

    fs.writeFileSync(`src/dto/create-${lowEntityClassName}.dto.ts`, res);
    // 3.读取并写入update.dto
    filePath = 'src/template/dto/update-template.dto.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    fs.writeFileSync(`src/dto/update-${lowEntityClassName}.dto.ts`, res);
    // 4.读取并写入entities
    filePath = 'src/template/entities/template.entity.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    res = res.replaceAll('// ${entity}', tempEntity);

    fs.writeFileSync(`src/entity/${lowEntityClassName}.entity.ts`, res);
    // 5.读取并写入service
    filePath = 'src/template/template.service.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    fs.writeFileSync(`src/service/${lowEntityClassName}.service.ts`, res);
    // 6.读取并写入controller
    filePath = 'src/template/template.controller.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    fs.writeFileSync(`src/admin/${lowEntityClassName}.controller.ts`, res);
    // 7.读取并写入controller
    filePath = 'src/template/template.api.template';

    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    fs.writeFileSync(`src/api/${lowEntityClassName}.api.ts`, res);
    // 8.读取并写入module
    filePath = 'src/template/template.module.template';
    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', entityClassName);
    res = res.replaceAll('template', lowEntityClassName);
    fs.writeFileSync(`src/module/${lowEntityClassName}.module.ts`, res);
    // 9.读取并写入vue

    let formValue = ``;
    let addTag = ``;
    let updateTag = ``;
    let formTag = ``;
    let queryTag = ``;
    let replaceTag = ``;

    jsonData.map((item) => {
      formValue = `${formValue}
${item.row} : null,`;

      addTag = `${addTag}
form.${item.row}= null`;

      updateTag = `${updateTag}
form.${item.row}=item.${item.row}`;

      formTag = `${formTag}
        <a-form-item label="${item.comment}">
          <a-input v-model="form.${item.row}" placeholder="请输入${item.comment}"/>
        </a-form-item>`;

      if (item.queryType == '1') {
        queryTag = `${queryTag}
        <a-form-item label="${item.comment}">
          <a-input v-model="query.${item.row}" placeholder="请输入${item.comment}"/>
        </a-form-item>`;
      }

      replaceTag = `${replaceTag}
        <a-table-column title="${item.comment}" data-index="${item.row}" />`;
    });

    filePath = 'src/template/vue/index.template';
    res = fs.readFileSync(filePath).toString();
    res = res.replaceAll('${template}', lowEntityClassName);

    res = res.replace('// from value', formValue);
    res = res.replace('// 赋值 tag', addTag);
    res = res.replace('// update tag', updateTag);
    res = res.replace('<!-- form tag -->', formTag);
    res = res.replace('<!-- query tag -->', queryTag);
    res = res.replace('<!-- 替换tag -->', replaceTag);

    fs.writeFileSync(`public/${lowEntityClassName}.vue`, res);

    // 10.写入路由到权限表中
    // 新增
    await Permission.save({
      name: '新增' + menuName,
      method: Method.POST,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Api,
      componentName: `${lowEntityClassName}`,
    });

    await Permission.save({
      name: '分页查询' + menuName,
      method: Method.GET,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Api,
      componentName: `${lowEntityClassName}`,
    });

    await Permission.save({
      name: '根据id查询' + menuName,
      method: Method.GET,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Api,
      componentName: `${lowEntityClassName}`,
    });

    await Permission.save({
      name: '更新' + menuName,
      method: Method.PATCH,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Api,
      componentName: `${lowEntityClassName}`,
    });

    await Permission.save({
      name: '删除' + menuName,
      method: Method.DELETE,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Api,
      componentName: `${lowEntityClassName}`,
    });

    await Permission.save({
      name: menuName + '管理',
      method: Method.GET,
      path: `/${lowEntityClassName}`,
      sort: 0,
      type: Type.Page,
      componentName: `${lowEntityClassName}`,
    });
  }

  async generateLike() {}
}
